import argparse
import os
import re


def count_characters(file_path):
    """Count the number of characters in the given file."""
    with open(file_path, 'r', encoding='utf-8') as file:
        return len(file.read())


def count_words(file_path):
    """Count the number of words in the given file."""
    with open(file_path, 'r', encoding='utf-8') as file:
        return len(file.read().split())


def count_lines(file_path):
    """Count the lines, including code lines, empty lines, and comment lines."""
    code_lines = 0
    empty_lines = 0
    comment_lines = 0

    # 正则表达式用于匹配注释行
    comment_pattern = re.compile(r'^\s*(#|//)')

    with open(file_path, 'r', encoding='utf-8') as file:
        for line in file:
            stripped_line = line.strip()
            if stripped_line.startswith('#') or stripped_line.startswith('//'):
                comment_lines += 1
            elif stripped_line == '':
                empty_lines += 1
            else:
                code_lines += 1

    return {
        'code_lines': code_lines,
        'empty_lines': empty_lines,
        'comment_lines': comment_lines
    }


def main():
    parser = argparse.ArgumentParser(description="Count characters, words, or lines in a file.")

    # Adding arguments
    parser.add_argument('file', type=str, help="The path to the file.")
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-c', '--characters', action='store_true', help="Count characters.")
    group.add_argument('-w', '--words', action='store_true', help="Count words.")
    group.add_argument('-l', '--lines', action='store_true', help="Count lines (code, empty, comments).")

    # Parse the arguments
    args = parser.parse_args()

    file_path = args.file

    # Check if the file exists
    if not os.path.exists(file_path):
        print(f"Error: The file {file_path} does not exist.")
        return

    if args.characters:
        print(f"Number of characters in '{file_path}': {count_characters(file_path)}")
    elif args.words:
        print(f"Number of words in '{file_path}': {count_words(file_path)}")
    elif args.lines:
        line_stats = count_lines(file_path)
        print(f"Lines statistics for '{file_path}':")
        print(f"Code lines: {line_stats['code_lines']}")
        print(f"Empty lines: {line_stats['empty_lines']}")
        print(f"Comment lines: {line_stats['comment_lines']}")


if __name__ == "__main__":
    main()